import binascii

import numpy


class StartSplit:
    def __init__(self, protocol_string, str_datas):
        self.protocol_string = protocol_string
        self.str_datas = str_datas
        self.items = {}

    def start_split(self):
        for protocol in self.protocol_string:
            protocol_data = self.slice_string(str_data=self.str_datas, start_index=protocol.get("start_index"),
                                              length=protocol.get("length"))
            hex_to_datas = self.list_of_chars(protocol_data)
            if len(hex_to_datas) == 0 or len(hex_to_datas) != protocol.get("length"):
                pass
            else:
                if protocol.get("type") == "HEX":
                    hex_reverse_datas = hex_to_datas[::-1]
                    decimal_data = "".join(hex_reverse_datas)
                    hex_decimal = self.hex_to_decimal(decimal_data)
                    if "enum" in protocol.keys():
                        for items in protocol["enum"]:
                            if str(hex_decimal) in items:
                                self.items[protocol.get("name")] = items
                    else:
                        if "电量" in protocol.get("name"):
                            self.items[protocol.get("name")] = f"{hex_decimal / 100} kwh"
                        elif "费用" in protocol.get("name"):
                            self.items[protocol.get("name")] = f"{hex_decimal / 1000000} 元"
                        else:
                            self.items[protocol.get("name")] = hex_decimal
                elif protocol.get("type") == "time":
                    year = self.hex_to_decimal(hex_to_datas[0])
                    month = self.hex_to_decimal(hex_to_datas[1])
                    day = self.hex_to_decimal(hex_to_datas[2])
                    hour = self.hex_to_decimal(hex_to_datas[3])
                    minutes = self.hex_to_decimal(hex_to_datas[4])
                    second = self.hex_to_decimal(hex_to_datas[5])
                    formatted_time = f"{year}年{month}月{day}日{hour}时{minutes}分{second}秒"
                    self.items[protocol.get("name")] = formatted_time
                elif protocol.get("type") == "ASCII":
                    ASCII_DATA = self.hex_to_ascii(protocol_data).replace("\x00", "").replace("\x04", "")
                    self.items[protocol.get("name")] = ASCII_DATA
        return self.items

    # 将16进制转化为10进制
    def hex_to_decimal(self, star_data):
        decimal_star_data = int(star_data, 16)
        return decimal_star_data

    # 将字符串每2位进行切割存到列表中
    def list_of_chars(self, str_data):
        list_of_chars = [str_data[i:i + 2] for i in range(len(str_data)) if i % 2 == 0]
        return list_of_chars

    # 根据报文协议模板的索引进行切割
    def slice_string(self, str_data, start_index, length):
        str_data = str_data[28:len(str_data)]
        return str_data[start_index * 2:(start_index + length) * 2]

        # 16进制转为ASSIC

    def hex_to_ascii(self, hex_string):
        ascii_string = binascii.unhexlify(hex_string).decode("utf-8")
        return ascii_string.strip('\n')


def slice_string(str_data, start_index, length):
    str_data = str_data[28:len(str_data)]
    return str_data[start_index * 2:(start_index + length) * 2]


# 16进制转为ascii格式
def hex_to_ascii(hex_string):
    try:
        ascii_string = binascii.unhexlify(hex_string).decode("utf-8")
        return ascii_string
    except Exception as e:
        return str(e)


# 16进制转为10进制
def hex_to_decimal(star_data):
    decimal_star_data = int(star_data, 16)
    return decimal_star_data


def list_of_reverse_chars(str_data):
    list_of_chars = [str_data[i:i + 2] for i in range(len(str_data)) if i % 2 == 0]
    reverse_data = ''.join(list_of_chars[::-1])
    return reverse_data.strip('\n')


#
class Converter:
    # 10进制转为16进制的HEX格式
    @staticmethod
    def decimal_to_hex(decimal_number, length):
        hex_result = format(decimal_number, '0{}X'.format(2 * length))
        return hex_result

    # 将10进制转化为16进制的ASCII格式，并使用0在右侧补全固定位数
    @staticmethod
    def ascii_to_hex(ascii_string, length=None):
        try:
            hex_string = binascii.hexlify(ascii_string.encode("utf-8")).decode("utf-8")
            padded_hex_string = hex_string.ljust(2 * length, '0')
            return padded_hex_string
        except Exception as e:
            return str(e)

    @staticmethod
    # 16进制转为ASCII进制
    def hex_to_ascii(hex_string):
        try:
            ascii_string = binascii.unhexlify(hex_string).decode("utf-8")
            return ascii_string
        except Exception as e:
            return str(e)

    @staticmethod
    # 16进制转为10进制
    def hex_to_decimal(star_data):
        decimal_star_data = int(star_data, 16)
        return decimal_star_data


def list_of_chars(str_data):
    list_of_chars = [str_data[i:i + 2] for i in range(len(str_data)) if i % 2 == 0]
    str_data = ''.join(list_of_chars[::-1])
    return str_data.lower()


class StringManipulator:
    @staticmethod
    def replace_substring(str_datas, replace_data, start_index, length):
        str_data = str_datas[28:len(str_datas)]
        end_index = 2 * (start_index + length)
        result = str_datas[:28] + str_data[:2 * start_index] + replace_data + str_data[end_index:]
        return result
